package org.example1.service;

import jakarta.annotation.PostConstruct;
import org.example1.api.ProductApi;
import org.example1.mapper.OrderMapper;
import org.example1.model.OrderInfo;
import org.example1.model.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private static AtomicInteger atomicInteger = new AtomicInteger(1);

    private List<ServiceInstance> instances;

    /**
     * 在bean初始化完成之后，自动执行
     */
    @PostConstruct
    public void init() {
        instances = discoveryClient.getInstances("product-service");
    }

//    public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//        //String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
//        //根据应用名称获取服务列表
//        int index = atomicInteger.getAndIncrement() % instances.size();
//        //服务可能有多个，获取第一个
//        EurekaServiceInstance instance = (EurekaServiceInstance) instances.get(index);
//        //拼接url
//        String url = instance.getUri() + "/product/" + orderInfo.getProductId();
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

//    public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//        String url = "http://product-service/product/" + orderInfo.getProductId();
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

    @Autowired
    private ProductApi productApi;

    public OrderInfo selectOrderById(Integer id) {
        OrderInfo orderInfo = orderMapper.selectOrderById(id);
        ProductInfo productInfo = productApi.getProductById(orderInfo.getProductId());
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
